package com.miao.ucenter.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.miao.ucenter.mapper.XcMenuMapper;
import com.miao.ucenter.mapper.XcUserMapper;
import com.miao.ucenter.model.dto.AuthParamsDto;
import com.miao.ucenter.model.dto.XcUserExt;
import com.miao.ucenter.model.po.XcMenu;
import com.miao.ucenter.model.po.XcUser;
import com.miao.ucenter.service.OuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

import java.applet.AppletContext;
import java.util.ArrayList;
import java.util.List;

@Component
public class UserServiceImpl implements UserDetailsService {

    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private XcMenuMapper menuMapper;

    //传入的参数是AuthParamsDto
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        AuthParamsDto authParamsDto = null;
        try {
            authParamsDto = JSON.parseObject(s, AuthParamsDto.class);
        } catch (Exception e) {
            throw new RuntimeException("验证参数不符合要求");
        }
        //查看登陆类型(微信，密码)
        String authType = authParamsDto.getAuthType();
        //获取对应的bean
        OuthService outhService = applicationContext.getBean(authType + "_authservice", OuthService.class);
        //调用方法
        XcUserExt xcUserExt = outhService.excute(authParamsDto);

        //封装返回对象
        return getUserDetails(xcUserExt);

    }

    //封装权限信息
    private UserDetails getUserDetails(XcUserExt xcUserExt){
        //封装为UserDetails
        //封装权限
        List<XcMenu> xcMenus = menuMapper.selectPermissionByUserId(xcUserExt.getId());
        List<String> auths = new ArrayList<>();
        for (XcMenu xcMenu : xcMenus) {
            auths.add(xcMenu.getCode());
        }
        String[] authorities = auths.toArray(new String[0]);
        xcUserExt.setPermissions(auths);
        //将用户信息全部保存
        String user_detail = JSON.toJSONString(xcUserExt);
        //返回信息
        return User.withUsername(user_detail).password(xcUserExt.getPassword()).authorities(authorities).build();

    }
}
